package com.colin.jipay;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.colin.jipay.activity.MainActivity;
import com.colin.jipay.alipay_hook.AlipayHook;
import com.colin.jipay.config.ActConst;
import com.colin.jipay.nxys.helper.NxysHelper;
import com.colin.jipay.pinduoduo_hook.PDDBuyerHook;
import com.colin.jipay.pinduoduo_hook.PDDSellerHook;
import com.colin.jipay.starpos.StarPosHelper;
import com.colin.jipay.taobao_hook.QianNiuHook;
import com.colin.jipay.taobao_hook.TaobaoHook;
import com.colin.jipay.unionpay.UnionHook;
import com.colin.jipay.utils.LogUtil;
import com.colin.jipay.utils.PayHelperUtils;
import com.colin.jipay.weidian.WDHelper;
import com.colin.jipay.weidian.WDShopHelper;

import java.util.HashMap;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * author : Colin
 * e-mail : Colin12138@gmail.com
 * qq     : 3327763437
 * date   : 2019/4/32:04 AM
 */
public class Main implements IXposedHookLoadPackage {

    //拼多多买家主进程名
    private static final String PINDUODUO_PROCESS_NAME_BUYER = "com.xunmeng.pinduoduo";
    //拼多多商家主进程名
    private static final String PINDUODUO_PROCESS_NAME_BUSINESS = "com.xunmeng.merchant";

    public static String TAOBAO_PACKAGE = "com.taobao.taobao";
    public static String UNION_PACKAGE = "com.unionpay";
    public static String ALIPAY_PACKAGE = "com.eg.android.AlipayGphone";

    public static boolean UNION_PACKAGE_ISHOOK = false;
    public static boolean IS_TAOBAO_HOOK = false;
    private static boolean IS_QNHOOK = false;
    private static boolean IS_SPHOOK = false;
    private static boolean IS_WDHOOK = false;
    private static boolean IS_WD_SHOP_HOOK = false;
    private static boolean IS_NXYS_HOOK = false;
    public static boolean ALIPAY_PACKAGE_ISHOOK = false;
    private static Context mContext;

    @Override
    public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
//        if (loadPackageParam.appInfo == null || (loadPackageParam.appInfo.flags & (ApplicationInfo.FLAG_SYSTEM
//                | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)
//                ) != 0 ){
//            return;
//        }

        final String packageName = loadPackageParam.packageName;
        final String processName = loadPackageParam.processName;
        XposedBridge.log("加载应用包名=" + packageName);
        if (TAOBAO_PACKAGE.equals(packageName)) {
            XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    Context context = (Context) param.thisObject;
                    mContext = context;
                    ClassLoader classLoader = context.getClassLoader();
                    if (TAOBAO_PACKAGE.equals(processName) && !IS_TAOBAO_HOOK) {
                        IS_TAOBAO_HOOK = true;
                        StartTaobaoReceived startTaobaoReceived = new StartTaobaoReceived();
                        IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction(ActConst.TAOBAO_PAY);
                        intentFilter.addAction("com.colin.taobao.getnick");
                        context.registerReceiver(startTaobaoReceived, intentFilter);
                        new TaobaoHook().hook(classLoader, context);
                        PayHelperUtils.sendmsg(context, "淘宝监听启动");
                    }
                }
            });
        }

        if (ALIPAY_PACKAGE.equals(packageName)) {
            try {
                XposedHelpers.findAndHookMethod(Application.class, "attach", Context.class, new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        Context context = (Context) param.args[0];
                        ClassLoader appClassLoader = context.getClassLoader();

                        if (ALIPAY_PACKAGE.equals(processName) && !ALIPAY_PACKAGE_ISHOOK) {
                            ALIPAY_PACKAGE_ISHOOK = true;
                            //注册广播
                            StartAlipayReceived startAlipay = new StartAlipayReceived();
                            IntentFilter intentFilter = new IntentFilter();
                            intentFilter.addAction("com.colin.alipay.start");
                            intentFilter.addAction("com.payhelper.alipay_payee.start");
                            context.registerReceiver(startAlipay, intentFilter);

                            XposedBridge.log("handleLoadPackage: " + packageName);
                            PayHelperUtils.sendmsg(context, "支付宝Hook成功，当前支付宝版本:" + PayHelperUtils.getVerName(context));
                            new AlipayHook().hook(appClassLoader, context);
                        }

                    }
                });


            } catch (Throwable e) {
                XposedBridge.log(e);
            }
        }

        if (packageName.equals("com.taobao.qianniu")) {
            XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    Context context = (Context) param.thisObject;
                    ClassLoader classLoader = context.getClassLoader();
                    if (processName.equals("com.taobao.qianniu") && !IS_QNHOOK) {
                        IS_QNHOOK = true;
                        new QianNiuHook().hook(context, classLoader);
                        PayHelperUtils.sendmsg(context, "千牛监听启动");
                    }
                }
            });

        }
        if (UNION_PACKAGE.equals(loadPackageParam.packageName)) {
            //
            XposedHelpers.findAndHookMethod(Application.class, "attach", Context.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    final Context context = (Context) param.args[0];
                    ClassLoader classLoader = context.getClassLoader();
                    XposedBridge.log("<===>" + processName);

                    if (UNION_PACKAGE.equals(processName) && !UNION_PACKAGE_ISHOOK) {
                        UNION_PACKAGE_ISHOOK = true;
                        StartUnionReceived unionReceived = new StartUnionReceived();
                        IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction("com.colin.union.start");
                        intentFilter.addAction("com.colin.union.notify");
                        context.registerReceiver(unionReceived, intentFilter);
                        PayHelperUtils.sendmsg(context, "unionPay注册广播完成");

                        new UnionHook().hook(classLoader, context);
                    }
                }
            });
        }
        if (packageName.equals("com.newland.satrpos.starposmanager")) {
            XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
                @Override
                protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                    super.afterHookedMethod(param);
                    Context context = (Context) param.thisObject;
                    ClassLoader classLoader = context.getClassLoader();
                    if (processName.equals("com.newland.satrpos.starposmanager") && !IS_SPHOOK) {
                        IS_SPHOOK = true;
//                        PayHelperUtils.sendmsg(context,"星管家监听启动");
                        XposedBridge.log("星管家监听启动");
                        StarPosHelper.hookStarPosQueryTrans(loadPackageParam, classLoader.loadClass(StarPosHelper.CLS_TRANS_ACTION_QUERY));
                        StarPosHelper.hookActivityStarPosQueryTrans(loadPackageParam, classLoader.loadClass(StarPosHelper.ACTIVITY_TRANS_QUERY));
                        //获取查询交易类的实例对象，才能使用
                        StarPosHelper.instanceQueryPresenterClass = XposedHelpers.newInstance(classLoader.loadClass(StarPosHelper.CLS_TRANS_ACTION_QUERY));
                        StarPosHelper.instanceQueryActivity = XposedHelpers.newInstance(classLoader.loadClass(StarPosHelper.ACTIVITY_TRANS_QUERY));
                    }
                }
            });
        }
        if (loadPackageParam.packageName.equals("com.koudai.weidian.buyer")) {
            if (loadPackageParam.processName.equals("com.koudai.weidian.buyer") && !IS_WDHOOK) {
                IS_WDHOOK = true;
                XposedBridge.log("hook到了微店进程");
                hookWeiDianProc(loadPackageParam);
            }
        }
        if (loadPackageParam.packageName.equals("com.koudai.weishop")) {
            if (loadPackageParam.processName.equals("com.koudai.weishop") && !IS_WD_SHOP_HOOK) {
                IS_WD_SHOP_HOOK = true;
                XposedBridge.log("hook到了微店商家版进程");
                hookWeiDianShopProc(loadPackageParam);
            }
        }
        if (loadPackageParam.packageName.equals("com.buybal.buybalpay.nxy")) {
            if (loadPackageParam.processName.equals("com.buybal.buybalpay.nxy") && !IS_NXYS_HOOK) {
                IS_NXYS_HOOK = true;
                XposedBridge.log("hook到了农信易扫进程");
                hookNXYSProc(loadPackageParam);
            }
        }


        //HOOK 拼多多买家
        if (packageName.equals(PINDUODUO_PROCESS_NAME_BUYER)) {

            XposedBridge.log("HOOK【拼多多买家】主进程：" + packageName);
            PDDBuyerHook pddBuyerHook = new PDDBuyerHook(loadPackageParam);
            pddBuyerHook.hookAutoOrders();
            pddBuyerHook.hookPddAlipay();
        }

        //HOOK 拼多多商家
        if (packageName.equals(PINDUODUO_PROCESS_NAME_BUSINESS)) {

            XposedBridge.log("HOOK【拼多多商家】主进程：" + packageName);
            PDDSellerHook pddSellerHook = new PDDSellerHook(loadPackageParam);
            pddSellerHook.hookPddOrderInfo();
        }
    }

    /**
     * hook农信易扫 进程
     *
     * @param loadPackageParam
     */
    private void hookNXYSProc(XC_LoadPackage.LoadPackageParam loadPackageParam) {
        XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                String cls_name = param.thisObject.getClass().getName();
                XposedBridge.log("loadActivity=" + cls_name);
                if (cls_name.equals("com.buybal.buybalpay.activity.WelcomeActivity")) {

                } else if (cls_name.equals("com.buybal.buybalpay.activity.HomeActivity")) {
                    //hook到二维码被创建，此时是用户已经登录了，做一些对象的初始化操作
                    NxysHelper.hookGetQrLink(param.thisObject.getClass().getClassLoader());
                    //在homeActivity这个页面注册一个广播接收器，不会被销毁
                    NxysHelper.registNxysReceiver((Context) param.thisObject);
                    //循环执行获取订单数据的任务，如果没有登录就会跳过这一次
                    NxysHelper.scheduleGetOrdersTask((Context) param.thisObject);
                }
            }
        });
    }

    private void hookWeiDianProc(XC_LoadPackage.LoadPackageParam lpparam) {
        XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                String cls_name = param.thisObject.getClass().getName();
                XposedBridge.log("loadActivity=" + cls_name);
                if (cls_name.equals("com.vdian.transaction.order.OrderConfirmActivity")) {
                    XposedBridge.log("loadClass=com.vdian.transaction.order.OrderConfirmActivity");
                    //进入到了主界面正常所有的类都加载好了
                } else if (cls_name.equals("com.vdian.android.wdb.main.ui.activity.MainTabsActivity")) {
                    WDHelper.dumpClass(param.thisObject.getClass().getClassLoader().loadClass("order.b.b"));
                    WDHelper.hookOrderConfirmActivityOnCreate(param.thisObject.getClass().getClassLoader());
                } else if (cls_name.equals("com.koudai.payment.activity.PayWeexRenderActivity")
                        || cls_name.equals("com.koudai.payment.activity.PaymentActivity")) {
                    WDHelper.hookAliPayReq(param.thisObject.getClass().getClassLoader());
                }
            }
        });
    }


    private void hookWeiDianShopProc(XC_LoadPackage.LoadPackageParam lpparam) {
        XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                String cls_name = param.thisObject.getClass().getName();
                XposedBridge.log("loadActivity=" + cls_name);
                if (cls_name.equals("com.koudai.weishop.main.ui.activity.TabHostActivity")) {
                    WDHelper.dumpClass(param.thisObject.getClass().getClassLoader().loadClass("com.koudai.weishop.order.page.list.model.OrderListItem$SubOrderVOList"));

                    WDShopHelper.hookOrderListGetData(param.thisObject.getClass().getClassLoader());
                }
            }
        });
    }

    //淘宝广播
    class StartTaobaoReceived extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case "com.colin.taobao.getcode":
                    Intent intent1 = new Intent(context, XposedHelpers.findClass("com.taobao.tao.purchase.activity.PurchaseActivity", mContext.getClassLoader()));
//
                    HashMap<String, String> data = new HashMap();
                    data.put("buyNow", "true");
                    data.put("itemId", intent.getStringExtra("itemid"));
                    data.put("skuId", intent.getStringExtra("skuid"));
                    data.put("quantity", "1");
                    data.put("serviceId", "");
                    data.put("tgKey", "");
                    data.put("bookingDate", "");
                    data.put("entranceDate", "");
                    data.put("exParams", "");
                    intent1.putExtra("purchase_from", 2);
                    intent1.putExtra("referrer", "https://detail.tmall.com/item.htm?id=543763493182&ali_trackid=30_03d7793f67a71748408cd8c475126ee8&spm=a21bo.2017.201863-2.1");
                    intent1.putExtra("URL_REFERER_ORIGIN", "https://h5.m.taobao.com/awp/base/buy.htm");
                    intent1.putExtra("buildOrderParams", data);
                    context.startActivity(intent1);
                    break;
                case "com.colin.taobao.getnick":
                    Intent intent2 = new Intent(context, XposedHelpers.findClass("com.taobao.mytaobao.setting.UserProfileActivity", mContext.getClassLoader()));
                    context.startActivity(intent2);
                    break;
            }

        }
    }

    //自定义启动支付宝广播
    class StartAlipayReceived extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            XposedBridge.log("启动支付宝Activity");
            if ("com.payhelper.alipay_payee.start".equals(intent.getAction())) {
                Intent intent2 = new Intent(context, XposedHelpers.findClass("com.alipay.mobile.payee.ui.PayeeActivityNew", context.getClassLoader()));
                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent2.putExtra("mark", intent.getStringExtra("mark"));
                intent2.putExtra("money", intent.getStringExtra("money"));
                intent2.putExtra("uid", intent.getStringExtra("uid"));
                context.startActivity(intent2);
            } else if ("com.colin.alipay.start".equals(intent.getAction())) {
                Intent intent1 = new Intent(context, XposedHelpers.findClass("com.alipay.mobile.payee.ui.PayeeQRSetMoneyActivity", context.getClassLoader()));
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent1.putExtra("mark", intent.getStringExtra("mark"));
                intent1.putExtra("money", intent.getStringExtra("money"));
                context.startActivity(intent1);

            }

        }
    }

    //自定义云闪付产码&结果回调广播
    class StartUnionReceived extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            PayHelperUtils.sendmsg(context, intent.getAction());
            switch (intent.getAction()) {
                case "com.colin.union.start":
                    Intent intent1 = new Intent(context, XposedHelpers.findClass("com.unionpay.activity.payment.UPActivityP2PTransferSetAmount", context.getClassLoader()));
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent1);
                    XposedBridge.log("===union产码start===");
                    String money = intent.getStringExtra("money");
                    String mark = intent.getStringExtra("mark");
                    XposedBridge.log(">>>>" + mark);
                    UnionHook.doGetQrCode(money, mark);
                    break;
                case "com.colin.union.notify":
                    XposedBridge.log("===union结果回调===");

                    break;
            }
        }
    }
}
